#include "list.h"
#include <iostream>
using namespace std;

void List::InitList() {
	_head=new Node;
	_head->next=NULL;
}

bool List::ListInsert(int pos,int num) {
	int i=0;
	Node* p=_head;
	while(i<pos-1&&p!=NULL) {
		p=p->next;	
		++i;
	}
	if(p==NULL) {
		return false;
	} else {
		Node* temp=new Node;
		temp->item=num;
		temp->next=p->next;
		p->next=temp;
		return true;
	}
}

void List::ListDisp() {
	Node* p=_head->next;
	while(p!=NULL) {
		cout << p->item << " ";
		p=p->next;
	}
	cout << endl;
}

void List::ClearList() {
	Node* p=_head;
	Node* q=p->next;
	_head->next=NULL;
	while(q!=NULL) {
		delete(p);
		p=q;
		q=p->next;
	}
	delete(p);
}

void List::Union(List& La,List Lb) {
	Node* pa=_head->next;
	Node* pb=(Lb._head)->next;
	int pos=1;
	while(pa&&pb) {
		if(pa->item<pb->item) {
			pa=pa->next;
			++pos;
		} else if(pa->item>pb->item){
			La.ListInsert(pos,pb->item);
			pb=pb->next;
		} else {
			pb=pb->next;
		}
	}
	if(pa==NULL) {
		while(pb!=NULL) {
			La.ListInsert(pos,pb->item);
			pb=pb->next;
			++pos;
		}
	}

}

void List::MergeList(List La,List Lb,List &Lc) {
	Node* pa=(La._head)->next;
	Node* pb=(Lb._head)->next;
	Node* pc=Lc._head;
	int pos=1;
	while(pa&&pb) {
		if(pa->item<=pb->item) {
			Lc.ListInsert(pos++,pa->item);
			pa=pa->next;
		} else {
			Lc.ListInsert(pos++,pb->item);
			pb=pb->next;
		}
	}
	if(pa==NULL) {
		while(pb!=NULL) {
			Lc.ListInsert(pos++,pb->item);
			pb=pb->next;
		}
	} else { 
		while(pa!=NULL) {
			Lc.ListInsert(pos++,pa->item);
			pa=pa->next;
		}
	}
	
}
